package com.itheima.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.Comment;
import com.itheima.domain.mongo.Movement;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.CommentService;
import com.itheima.service.mongo.MovementService;
import com.itheima.vo.*;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.*;

@Component
public class UserManager {

    @DubboReference
    UserInfoService userInfoService;

    @DubboReference
    MovementService movementService;

    @DubboReference
    CommentService commentService;

    @Autowired
    StringRedisTemplate redisTemplate;

    public ResponseEntity findByPage(Integer pageNum, Integer pageSize) {
        PageBeanVo pageBeanVo = userInfoService.findByPage(pageNum, pageSize);
        List<UserInfo> items = (List<UserInfo>) pageBeanVo.getItems();
        List<UserInfoVo2> list=new ArrayList<>();
        for (UserInfo userInfo : items) {
            UserInfoVo2 userInfoVo2=new UserInfoVo2();
            BeanUtil.copyProperties(userInfo,userInfoVo2);
            if(!redisTemplate.hasKey("status"+userInfo.getId())){
                redisTemplate.opsForValue().set("status"+userInfo.getId(),"1");
                userInfoVo2.setUserStatus("1");
                list.add(userInfoVo2);
            }else{
                String userStatus= redisTemplate.opsForValue().get("status"+userInfoVo2.getId());
                userInfoVo2.setUserStatus(userStatus);
                list.add(userInfoVo2);
            }
        }
        pageBeanVo.setItems(list);
        return ResponseEntity.ok(pageBeanVo);
    }

    public ResponseEntity findUserInfoById(Long userId) {
        UserInfo userInfo = userInfoService.findById(userId);
        UserInfoVo2 userInfoVo2=new UserInfoVo2();
        BeanUtil.copyProperties(userInfo,userInfoVo2);
        if(!redisTemplate.hasKey("status"+userInfoVo2.getId())){
            redisTemplate.opsForValue().set("status"+userInfoVo2.getId(),"1");
            userInfoVo2.setUserStatus("1");
        }else{
            String userStatus= redisTemplate.opsForValue().get("status"+userInfoVo2.getId());
            userInfoVo2.setUserStatus(userStatus);
        }
        return ResponseEntity.ok(userInfoVo2);
    }

    public ResponseEntity findMovementByCondition4Page(Long userId, Integer state, Integer pageNum, Integer pageSize) {
        //1.判断uid是否为空,若不为空查询userInfo
        UserInfo userInfo = null;
        if (userId!=null) {
            userInfo = userInfoService.findById(userId);
        }

        //2.远程调用service查询pageBeanvo
        PageBeanVo pageBeanVo = movementService.findMovementByCondition4Page(userId, state, pageNum, pageSize);

        //3.获取pageBeanVo中动态集合
        List<Movement> items = (List<Movement>) pageBeanVo.getItems();

        //4.遍历动态集合,获取每个动态,若uid为空是查询动态的发布人userInfo,将动态和userInfo封装成MovementVo对象,将vo放入声明好的voList中
        List<MovementVo> voList = new ArrayList<>();
        if (CollUtil.isNotEmpty(items)) {
            for (Movement movement : items) {
                //若uid为空是查询动态的发布人userInfo
                if (userId == null) {
                    userInfo = userInfoService.findById(movement.getUserId());
                }

                //将动态和userInfo封装成MovementVo对象
                MovementVo vo = new MovementVo();

                //先userInfo后movement
                vo.setUserInfo(userInfo);
                vo.setMovement(movement);

                //单独处理下日期
                vo.setCreateDate(DateUtil.formatDateTime(new Date(movement.getCreated())));

                voList.add(vo);
            }
        }

        //5.将voList设置给pageBeanVo
        pageBeanVo.setItems(voList);
        //6.返回pageBeanVo即可
        return ResponseEntity.ok(pageBeanVo);
    }

    public ResponseEntity findMovementById(String movementId) {
        //1.远程调用service查询动态详情
        Movement movement = movementService.findById(new ObjectId(movementId));

        //2.远程调用service查询动态发布人userInfo
        UserInfo userInfo = userInfoService.findById(movement.getUserId());

        //3.封装MovementVo对象且返回
        MovementVo vo = new MovementVo();
        //先userInfo后movement
        vo.setUserInfo(userInfo);
        vo.setMovement(movement);

        //单独处理下时间
        vo.setCreateDate(DateUtil.formatDateTime(new Date(movement.getCreated())));

        return ResponseEntity.ok(vo);
    }

    public ResponseEntity findMovementComemntByPage(String movementId, Integer pageNum, Integer pageSize) {
        //1.远程调用commentService查询pageBeanVo
        PageBeanVo pageBeanVo = commentService.findCommentByPage(new ObjectId(movementId),2, pageNum, pageSize);

        //2.获取pageBeanVo中评论list
        List<Comment> items = (List<Comment>) pageBeanVo.getItems();

        //3.遍历评论list,获取每个评论,获取评论人的userInfo,将评论和userInfo封装CommentVo对象,将每个vo放入声明好的voList中
        List<CommentVo> voList = new ArrayList<>();
        if (CollUtil.isNotEmpty(items)) {
            items.forEach(comment -> {
                //获取评论人的userInfo,
                UserInfo userInfo = userInfoService.findById(comment.getUserId());

                //将评论和userInfo封装CommentVo对象,
                CommentVo vo = new CommentVo();
                vo.setId(comment.getId().toString());
                vo.setAvatar(userInfo.getAvatar());
                vo.setNickname(userInfo.getNickname());
                vo.setContent(comment.getContent());
                vo.setCreateDate(DateUtil.formatDateTime(new Date(comment.getCreated())));

                //将每个vo放入声明好的voList中
                voList.add(vo);
            });
        }

        //4.将voList设置给pageBeanVo
        pageBeanVo.setItems(voList);
        //5.返回pageBeanVo
        return ResponseEntity.ok(pageBeanVo);
    }

    //用户冻结
    public ResponseEntity freezeUser(Map<String,Object> map) {
        Integer userId = (Integer) map.get("userId");
        Integer freezingTime = Integer.valueOf((String)map.get("freezingTime"));

        //将用户状态存入redis
        if(freezingTime!=3){
            redisTemplate.opsForValue().set("status"+userId,"2", Duration.ofDays(freezingTime));
        }else{
            redisTemplate.opsForValue().set("status"+userId,"2");
        }

        //将冻结信息存入redis
        if(freezingTime!=3){
            redisTemplate.opsForValue().set("freeze"+userId, JSON.toJSONString(map), Duration.ofDays(freezingTime));
        }else{
            redisTemplate.opsForValue().set("freeze"+userId,JSON.toJSONString(map));
        }

        Map<String,String> map2=new HashMap<>();
        map.put("message","操作成功");
        return ResponseEntity.ok(map2);

    }

    public ResponseEntity unfreezeUser(Map<String, Object> map) {
        Integer userId = (Integer) map.get("userId");
        String reasonsForThawing = (String) map.get("reasonsForThawing");

        //将用户的状态修改
        redisTemplate.opsForValue().set("status"+userId,"1");

        //将冻结信息从redis中删除
        redisTemplate.delete("freeze"+userId);


        Map<String,String> map2=new HashMap<>();
        map.put("message","操作成功");
        return ResponseEntity.ok(map2);
    }
    //动态复审
    public ResponseEntity reviewMovement(String[] pushIdlist) {

        //遍历调用rpc
        for (String pushId : pushIdlist) {
            //查询movement对象
            Movement movement = movementService.findById(new ObjectId(pushId));//
            movement.setState(1);//改变参数
            movementService.update(movement);//回存
        }
        //返回map
        HashMap<String, String> map = new HashMap<>();
        map.put("message","审核通过~");
        return ResponseEntity.ok(map);
    }

    public ResponseEntity rejectedMovement(String[] pushIdlist) {
        //遍历
        for (String pushId : pushIdlist) {
            //获取对象
            Movement movement = movementService.findById(new ObjectId(pushId));
            movement.setState(2);//改变参数
            movementService.update(movement);//回存
        }
        //返回map.
        HashMap<String, String> map = new HashMap<>();
        map.put("message","审核通过~");
        return ResponseEntity.ok(map);
    }
}
